package main.java.com.bookmanager.controller;

import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import main.java.com.bookmanager.model.Book;
import main.java.com.bookmanager.service.BookService;
import main.java.com.bookmanager.util.Classify;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

@WebServlet("/books")
@MultipartConfig
public class BookServlet extends HttpServlet {
    private BookService bookService = new BookService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");
            switch (action) {
                case "add":
                    handleAddBook(request, response);
                    break;
                case "get":
                    handleGetBook(request, response);
                    break;
                case "update":
                    handleUpdateBook(request, response);
                    break;
                case "delete":
                    handleDeleteBook(request, response);
                    break;
                case "getAll":
                    handleGetAllBooks(request, response);
                    break;
                default:
                    out.println("未知操作类型");
            }
    }

    protected void handleGetBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Book book= null;
        try {
            Classify classify = Classify.valueOf(request.getParameter("classify"));
            int id = Integer.parseInt(request.getParameter("id"));
            book = bookService.getBooks(classify,id);
        } catch (IllegalArgumentException e) {
            out.println("无法找到相关书籍！");
        }
        out.println("<html><body>");
        out.println("<style>");
        out.println("  table { border-collapse: collapse; width: 100%; }");
        out.println("  th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }");
        out.println("  th { background-color: #f2f2f2; }");
        out.println("</style>");
        out.println("<h1>查询到的书籍</h1>");
        out.println("<table>");
        out.println("<tr>");
        out.println("<th>ID</th>");
        out.println("<th>名称</th>");
        out.println("<th>作者</th>");
        out.println("<th>类型</th>");
        out.println("<th>状态</th>");
        out.println("<th>在馆数量</th>");
        out.println("<th>借出</th>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("  <td>" + book.getBookId() + "</td>");
        out.println("  <td>" + book.getBookName() + "</td>");
        out.println("  <td>" + book.getBookAuthor() + "</td>");
        out.println("  <td>" + book.getClassify() + "</td>");
        out.println("  <td>" + book.getStatus() + "</td>");
        out.println("  <td>" + book.getQuantity() + "</td>");
        out.println("  <td>" + book.getLend() + "</td>");
        out.println("</tr>");
        out.println("</table>");
        out.println("</body></html>");
    }

    protected void handleAddBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
            try {
                Classify classify = Classify.valueOf(request.getParameter("classify"));
                int bookId = Integer.parseInt(request.getParameter("bookId"));
                String bookName = request.getParameter("bookName");
                String bookAuthor = request.getParameter("bookAuthor");
                String status = request.getParameter("status");
                int  quantity = Integer.parseInt(request.getParameter("quantity"));
                String result = bookService.addBook(classify, bookId, bookName, bookAuthor, status, quantity);
                out.println(result);
            } catch (Exception e) {
                out.println("添加图书时出现错误：" + e.getMessage());
            }
    }

    protected void handleUpdateBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
            try {
                Classify classify = Classify.valueOf(request.getParameter("oldClassify"));
                String oldBookName = request.getParameter("oldBookName");
                int bookId = Integer.parseInt(request.getParameter("bookId"));
                String bookName = request.getParameter("bookName");
                String bookAuthor = request.getParameter("bookAuthor");
                Classify newClassify = Classify.valueOf(request.getParameter("newClassify"));
                int quantity = Integer.parseInt(request.getParameter("quantity"));
                String status = request.getParameter("status");
                String result = bookService.amendBook(classify, oldBookName, bookId, bookName, bookAuthor, newClassify , status,  quantity);
                out.println(result);
            } catch (Exception e) {
                out.println("修改图书时出现错误：" + e.getMessage());
            }
    }

    protected void handleDeleteBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
            try {
                Classify classify = Classify.valueOf(request.getParameter("classify"));
                String query = request.getParameter("query");
                String result = bookService.deleteBook(classify, query);
                out.println(result);
            } catch (Exception e) {
                out.println("删除图书时出现错误：" + e.getMessage());
        }
    }

    protected void handleGetAllBooks(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<style>");
        out.println("  table { border-collapse: collapse; width: 100%; }");
        out.println("  th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }");
        out.println("  th { background-color: #f2f2f2; }");
        out.println("</style>");
        out.println("<h1>书籍列表</h1>");
        out.println("<table>");
        out.println("<tr>");
        out.println("<th>ID</th>");
        out.println("<th>名称</th>");
        out.println("<th>作者</th>");
        out.println("<th>类型</th>");
        out.println("<th>状态</th>");
        out.println("<th>在馆数量</th>");
        out.println("<th>借出</th>");
        out.println("</tr>");
        Classify classify = Classify.valueOf(request.getParameter("classify"));
        List<Book> bookList = bookService.getAllBooks(classify);
        List<Book> sortedList = bookList.stream()
                .sorted(Comparator.comparingInt(Book::getBookId))
                .collect(Collectors.toList());
        for (Book book : sortedList) {
            out.println("<tr>");
            out.println("  <td>" + book.getBookId() + "</td>");
            out.println("  <td>" + book.getBookName() + "</td>");
            out.println("  <td>" + book.getBookAuthor() + "</td>");
            out.println("  <td>" + book.getClassify() + "</td>");
            out.println("  <td>" + book.getStatus() + "</td>");
            out.println("  <td>" + book.getQuantity() + "</td>");
            out.println("  <td>" + book.getLend() + "</td>");
            out.println("</tr>");
        }
        out.println("</table>");
        out.println("</body></html>");
    }
}